<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/2
 * Time: 19:04
 */

namespace app\api\controller\v1;


use app\api\controller\BaseController;
use app\api\model\Money;
use app\api\service\Pay as PayService;
use app\api\service\Token as TokenService;
use app\api\service\RecyclePaidMessage;
use app\api\service\VirtualPay as VirtualPayService;
use app\api\model\Order as OrderModel;
use app\api\service\WxNotify;
use app\api\validate\IDMustBePositiveInt;
use app\api\validate\PagingParameter;
use app\lib\Exception\SuccessNotice;

/*
 * 小程序拉起微信支付需要的参数
 * timeStamp  时间戳
 * nonceStr   随机字符串
 * package   prepay_id=*
 * signType  签名类型  默认为MD5
 * paySign 签名
 * */

class Pay extends BaseController
{
    protected $beforeActionList=[
        'checkOnlyUserScope'=>['only'=>'getPreOrder,BuyPay'],
        'checkSuperScope' => ['only' => 'RecyclePay'],
        'checkBaseScope' => ['only' => 'getMoneyRecords']
    ];

    public function getPreOrder($id){
    //验证order id
        (new IDMustBePositiveInt())->toCheck();

        $payService = new PayService($id);
        return $payService->pay();
    }

    public function receiveNotify(){
        $wxNotify = new WxNotify();
        $wxNotify->Handle();
    }


    //  Virtual pay
    // cms 打款给用户
    public function RecyclePay($id){
        //验证order id
        (new IDMustBePositiveInt())->toCheck();

        $payService = new VirtualPayService($id);

        // 还要发送模版消息  payRecycleOrder
        $res = $payService->payRecycleOrder();
        if($res){

        // 发送模版消息
            $order = OrderModel::get($id);
            $recyclePaid = new RecyclePaidMessage();
            $msg = $recyclePaid->sendMsg($order);
            if($msg){
                throw new SuccessNotice();
            }

            throw new SuccessNotice([
                'errorCode' => 81000
            ]);
        }
    }

    public function BuyPay($id){
        //验证order id
        (new IDMustBePositiveInt())->toCheck();

        $payService = new VirtualPayService($id);

        $res =  $payService->payBuyOrder();
        if($res){
            throw new SuccessNotice();
            // return json(['money' => $res]);
        }
    }

    public function getMoneyRecords($page = 1){
        (new PagingParameter())->toCheck();
        $uid = TokenService::getCurrentUid();
        $moneyRecords = Money::getMoneyRecords($uid, $page);
        $currentMoney = Money::getCurrentMoney($uid);

        $res = [
            'current_money'=> $currentMoney,
            'current_page'=> $moneyRecords->currentPage(),
            'data'=> []
        ];

        if($moneyRecords->isEmpty()){
            return $res;
        }

        $res['data'] = $moneyRecords->toArray();
        return $res;
    }
}

